
'use strict';

const os = require("os");
const fs = require("fs");
const path = require("path");
const { exec } = require('child_process');




exports.onAfterBuild = function (options, result) {
    let resdir = 'assets';

    console.warn('path', __dirname)

    if (fs.existsSync(path.join(result.dest, 'data'))) {
        resdir = 'data';
    }
    let remoteJson = null;
    try {
        remoteJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../demo.json'), 'utf8'));
    } catch (error) {
        console.error(error);
    }

    console.warn(JSON.stringify(remoteJson));

    // let cmd = `node version_generator.js -v 1.0.0 -u http://${getIPAdress()}:${remote_port}/ -s ${path.join(result.dest, resdir)} -d ${path.join(Editor.Project.path, "assets")}`    
    // let cmd = `node version_generator.js -v 1.0.0 -u https://cdn.oss.wakuart.com/hotupdata/dev/data/ -s ${path.join(result.dest, resdir)} -d ${path.join(Editor.Project.path, "assets")}`    
    // let cmd = `node version_generator.js -v 1.0.2 -u https://files.wakuart.com/downloads/hotupdata/dev/data/ -s ${path.join(result.dest, resdir)} -d ${path.join(Editor.Project.path, "assets")}`    
    let cmd = `node version_generator.js -v ${remoteJson.version} -u ${remoteJson.remote_url} -s ${path.join(result.dest, resdir)} -d ${path.join(Editor.Project.path, remoteJson.save_path)}`    
    console.warn(cmd);

    exec(cmd, { cwd: Editor.Project.path }, (err, stdout, stderr) => {
        if (err) {
            console.error(err);
            return;
        }

        const source_path = path.join(Editor.Project.path, remoteJson.remote_path);
        const save_project = path.join(Editor.Project.path, remoteJson.save_path, "project.manifest");
        const save_version = path.join(Editor.Project.path, remoteJson.save_path, "version.manifest");
        const remote_project = path.join(source_path, "project.manifest");
        const remote_version = path.join(source_path, "version.manifest");
        try {
            fs.promises.copyFile(save_project, remote_project);
            fs.promises.copyFile(save_version, remote_version);
        } catch (error) {
            console.error(error);
        }
    });
}
